var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fs = require('fs').promises;
const cors = require('cors');
const mime = require('mime-types');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var grtRouter = require('./routes/grt');
var aiRouter = require('./routes/ai');

var app = express();



// 指定静态目录，这里假设 public 目录是你要暴露的目录
const staticDir = path.join(__dirname, './public/low-code/');

const API_PREFIX = '/api';

// 正确注册 .vue 文件的 MIME 类型
mime.types.vue = 'text/plain';

// 配置 CORS 中间件
app.use(cors({
  origin: '*', // 允许所有域名跨域访问
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  allowedHeaders: 'Content-Type,Authorization'
}));


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());


app.use('/api/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/grt/', grtRouter);
app.use('/api/ai/', aiRouter);


// 使用 express.static 中间件来提供静态文件服务
// app.use(express.static(staticDir));

// 静态文件服务，使用自定义的 MIME 类型映射
app.use(express.static(staticDir, {
  setHeaders: (res, filePath) => {
    const ext = path.extname(filePath).toLowerCase();

    // 为 .vue 文件强制设置正确的 Content-Type
    if (ext === '.vue') {
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    }
    if (ext === '.js') {
      res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    }
  }
}));

// 处理目录浏览请求
app.get(/^(?!\/api).*$/, async (req, res, next) => {

  // 如果是API请求，直接跳过此中间件
  if (req.path.startsWith(API_PREFIX)) {
    return next();
  }

  const reqPath = path.join(staticDir, req.path);

  // 获取当前域名和端口
  const host = req.get('host');

  try {
    const stats = await fs.stat(reqPath);

    if (stats.isDirectory()) {
      const entries = await fs.readdir(reqPath);
      const files = [];
      const directories = [];

      for (const entry of entries) {
        const entryPath = path.join(reqPath, entry);
        const entryStats = await fs.stat(entryPath);

        if (entryStats.isDirectory()) {
          directories.push(entry);
        } else {
          files.push(entry);
        }
      }

      let html = `
        <!DOCTYPE html>
        <html>
        <head>
          <title>模版代码: ${req.path}</title>
          <style>
            body { font-family: Arial, sans-serif; }
            ul { list-style-type: none; padding: 0; }
            li { margin: 5px 0; }
            .dir { color: blue; }
            .file { color: black; }
          </style>
        </head>
        <body>
          <h1>模版代码: ${req.path}</h1>
          <ul>
      `;

      if (req.path !== '/') {
        html += `<li><a href="${path.dirname(req.path)}">..</a></li>`;
      }

      directories.forEach(dir => {
        const encodedDir = encodeURIComponent(dir);
        html += `<li class="dir"><a href="${req.path === '/' ? '' : req.path}/${encodedDir}/">${dir}/</a></li>`;
      });

      files.forEach(file => {
        const encodedFile = encodeURIComponent(file);
        html += `<li class="file"><a href="http://${host}${req.path === '/' ? '' : req.path}/${encodedFile}">${file}</a></li>`;
      });

      html += `
          </ul>
        </body>
        </html>
      `;

      res.send(html);
    } else {
      next();
    }
  } catch (err) {
    next();
  }
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
  // createError(404)
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
